package com.kedacom.demo.spring.websocket.rpc.server;

import org.springframework.stereotype.Controller;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.kedacom.demo.spring.websocket.AbstractWebSocketServerHandler;
import com.kedacom.demo.spring.websocket.rpc.Request;
import com.kedacom.demo.spring.websocket.rpc.Response;
import com.kedacom.demo.spring.websocket.utils.JacksonUtils;

@Controller("rpcWebSocketServerHandler")
public class RPCWebSocketServerHandler extends AbstractWebSocketServerHandler {

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		super.handleTextMessage(session, message);

		String text = message.getPayload();
		Request request = JacksonUtils.fromJsonString(text, Request.class);
		Response response = new Response(request.getId(), request.getType(),
				String.format("Hello, %s!", request.getData()));
		String responseJsonStr = JacksonUtils.toJsonString(response);

		// 响应请求
		session.sendMessage(new TextMessage(responseJsonStr));
	}

}
